<?php

namespace App\Http\Controllers;

use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Requests\Company\UpdateCompanyResource;
use Illuminate\Support\Facades\Storage;

class CompanyController extends Controller
{
	/**
	 * Date: 2018/2/5
	 * @author George
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index()
    {
        return $this->success(Company::first());
    }

	/**
	 * 更新企业信息
	 *
	 * Date: 2018/2/5
	 * @author George
	 * @param UpdateCompanyResource $request
	 * @param Company $company
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function update(UpdateCompanyResource $request, Company $company)
    {
        $attributes = $this->validate($request, [
            'name' => 'required',
            'address' => 'nullable',
            'logo' => 'nullable',
            'contacts' => 'nullable',
            'telephone' => 'nullable',
            'mobile' => 'nullable',
        ],[
            'name.required' => '公司名称不能为空',
        ]);

        foreach ($attributes as $key => $value){
            $company->{$key} = $value;
        }

        $company->saveOrFail();

        return $this->updated($company);
    }

	/**
	 * 修改公司Logo
	 *
	 * Date: 2018/2/5
	 * @author George
	 * @param Request $request
	 * @param Company $company
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function modifyLogo(Request $request, Company $company)
	{
		$attributes = $this->validate($request, [
			'logo' => 'required|dimensions:max_width=120,max_height=120'
		]);

		$file = $attributes['logo'];
		$path = $file->store('logo', 'public');

		//将logo路径保存到数据库汇总
		$company->update(['logo' => Storage::url($path)]);

		return $this->success([
			'path' => Storage::url($path)
		]);
    }
}
